<template>
  <div>
    <div class="w-full flex justify-between">
      <h3 style="display: inline-block">
        {{ $t("business.workload.container_image") }}
      </h3>
      <el-button
        link
        icon="Edit"
        type="primary"
        @click="uiOpts.dialogModifyVersionVisible = true"
      >
        {{ $t("commons.button.click_to_edit") }}
      </el-button>
    </div>
    <li
      v-for="(item, index) in imagesData"
      :key="index"
      style="margin-left: 20px; font-size: 16px"
    >
      {{ item.name }}:{{ item.version }}
    </li>

    <el-dialog
      v-model="uiOpts.dialogModifyVersionVisible"
      :title="$t('commons.button.scale')"
      width="70%"
      :close-on-click-modal="false"
    >
      <complex-table v-loading="uiOpts.loading" :data="imagesData">
        <el-table-column
          :label="$t('business.workload.container_type')"
          prop="type"
          min-width="10"
        />
        <el-table-column
          :label="$t('business.workload.name')"
          prop="name"
          min-width="20"
          show-overflow-tooltip
        />
        <el-table-column
          :label="$t('business.workload.container_image')"
          prop="image"
          min-width="40"
          show-overflow-tooltip
        />
        <el-table-column
          :label="$t('business.workload.current_version')"
          prop="version"
          min-width="15"
        />
        <el-table-column
          :label="$t('business.workload.new_version')"
          prop="newVersion"
          min-width="20"
        >
          <template #default="{ row }">
            <KoDataItem v-model="row.newVersion" itemType="input" />
          </template>
        </el-table-column>
      </complex-table>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button
            size="small"
            @click="uiOpts.dialogModifyVersionVisible = false"
          >
            {{ $t("commons.button.cancel") }}
          </el-button>
          <el-button size="small" @click="updateWorkloadInfo">
            {{ $t("commons.button.confirm") }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
// import { updateWorkLoad } from "@/api/workloads";
import KoDataItem from "@/views/domain/kubeHud/views/components/ko-data-item/index.vue";
import ComplexTable from "@/views/domain/kubeHud/views/components/complex-table/index.vue";
import {
  Container,
  Deployment,
  useK8SApi
} from "@/views/domain/kubeHud/api/k8s";
import { onMounted, reactive, ref, watch } from "vue";
import { useI18n } from "vue-i18n";

const { workloadRepo } = useK8SApi();
const { t } = useI18n();

type Prop = {
  cluster?: string;
  resourceType?: string;
};
const props = defineProps<Prop>();
const yamlInfo = defineModel<Deployment>("yamlInfo");

// const editForm = ref<any>({});
const imagesData = ref<
  {
    type?: string;
    cType?: "container" | "initContainer";
    name?: string;
    image?: string;
    version?: string;
    newVersion?: string;
  }[]
>([]);

const uiOpts = reactive({
  loading: false,
  dialogModifyVersionVisible: false
});

const parseImage = (
  image: string
): { image: string; version: string; newVersion: string } => {
  const splitIdx = image.lastIndexOf(":");
  if (splitIdx === -1) {
    return {
      image,
      version: "",
      newVersion: ""
    };
  }
  return {
    image: image.substring(0, splitIdx),
    version: image.substring(splitIdx + 1),
    newVersion: image.substring(splitIdx + 1)
  };
};

const onInitData = () => {
  if (!yamlInfo.value.spec) {
    return;
  }

  yamlInfo.value?.spec?.template?.spec?.containers?.forEach(
    (item: Container) => {
      imagesData.value.push({
        type: t("business.workload.container"),
        name: item.name,
        cType: "container",
        ...parseImage(item.image)
      });
    }
  );

  yamlInfo.value?.spec?.template?.spec?.initContainers?.forEach(
    (item: Container) => {
      imagesData.value.push({
        type: t("business.workload.init_container"),
        name: item.name,
        cType: "initContainer",
        ...parseImage(item.image)
      });
    }
  );
};

const updateWorkloadInfo = () => {
  imagesData.value.forEach(item => {
    if (item.cType === "container") {
      const index =
        yamlInfo.value?.spec?.template?.spec?.containers?.findIndex(
          c => c.name === item.name
        ) ?? -1;

      if (index !== -1) {
        yamlInfo.value.spec.template!.spec!.containers[index].image =
          item.image + ":" + item.newVersion;
      }
    } else if (item.cType === "initContainer") {
      const index =
        yamlInfo.value?.spec?.template?.spec?.initContainers?.findIndex(
          c => c.name === item.name
        ) ?? -1;

      if (index !== -1) {
        yamlInfo.value.spec.template!.spec!.initContainers[index].image =
          item.image + ":" + item.newVersion;
      }
    }
  });

  workloadRepo
    .updateWorkLoad(
      props.cluster,
      props.resourceType,
      yamlInfo.value.metadata.namespace,
      yamlInfo.value.metadata.name,
      yamlInfo.value
    )
    .then(res => {
      uiOpts.dialogModifyVersionVisible = false;
    });
};

watch(
  () => yamlInfo.value,
  () => {
    imagesData.value = [];
    onInitData();
  },
  { immediate: true }
);

onMounted(() => {
  onInitData();
});
</script>

<style scoped></style>
